<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <!-- 搜索操作 -->
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
          <el-button
            class="collapse-btn"
            type="text"
            @click="toggleSearch"
            :icon="showSearch ? 'ArrowDownBold' : 'ArrowUpBold'"
          >
            {{ showSearch ? "收起" : "展开" }}
          </el-button>
        </div>
      </template>

      <!-- 查询条件 -->
      <el-form
        :model="queryParams"
        ref="distributorRef"
        :inline="true"
        v-show="showSearch"
        label-width="88px"
      >
        <!-- <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="queryParams.userId"
            placeholder="请输入用户ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="分销员编号" prop="distributorCode">
          <el-input
            v-model="queryParams.distributorCode"
            placeholder="请输入分销员编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="queryParams.realName"
            placeholder="请输入真实姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="身份证号" prop="identityCard">
          <el-input
            v-model="queryParams.identityCard"
            placeholder="请输入身份证号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="等级" prop="gradeId">
          <el-input
            v-model="queryParams.gradeId"
            placeholder="请输入所属等级"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="上级分销员" prop="fatherId">
          <el-input
            v-model="queryParams.fatherId"
            placeholder="请输入上级分销员"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="团队总人数" prop="teamCount">
          <el-input
            v-model="queryParams.teamCount"
            placeholder="请输入团队总人数"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="直接下级人数" prop="directCount">
          <el-input
            v-model="queryParams.directCount"
            placeholder="请输入直接下级人数"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="成为分销员时间" prop="bindTime">
          <el-date-picker
            clearable
            v-model="queryParams.bindTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择成为分销员时间"
          >
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="最后登录时间" prop="lastLoginTime">
          <el-date-picker
            clearable
            v-model="queryParams.lastLoginTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择最后登录时间"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:distributor:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:distributor:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:distributor:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:distributor:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Connection"
          @click="handleBindParent"
          v-hasPermi="['ruoyi:distributor:edit']"
          >上级绑定</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表单渲染 -->
    <el-table
      v-loading="loading"
      border
      resizable
      :data="distributorList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="序号"
        type="index"
        min-width="60"
        align="center"
        prop="distributorId"
      />
      <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
      <el-table-column
        label="分销员编号"
        min-width="150"
        align="center"
        prop="distributorCode"
      />
      <el-table-column
        label="真实姓名"
        align="center"
        min-width="120"
        prop="realName"
      />
      <!-- <el-table-column label="手机号" align="center" prop="mobile" /> -->
      <!-- <el-table-column label="身份证号" align="center" prop="identityCard" /> -->
      <el-table-column
        label="当前等级"
        align="center"
        min-width="120"
        prop="gradeName"
      />
      <!-- <el-table-column label="上级" align="center" prop="fatherId" /> -->
      <el-table-column label="上级" align="center" min-width="120">
        <template #default="scope">
          {{ getFatherName(scope.row.fatherId) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="团队人数" align="center" prop="teamCount" /> -->
      <!-- <el-table-column label="下级人数" align="center" prop="directCount" /> -->
      <el-table-column
        label="成为分销员时间"
        align="center"
        prop="bindTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.bindTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="最后登录时间"
        align="center"
        prop="lastLoginTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastLoginTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="认证状态" align="center" prop="authStatus">
        <template #default="scope">
          <dict-tag
            :options="refund_audit_status"
            :value="scope.row.authStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="备注信息"
        align="center"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        align="center"
        min-width="300"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- 添加审核操作 -->
          <template v-if="scope.row.authStatus === '0'">
            <el-button
              link
              type="success"
              icon="CircleCheck"
              @click="handleApprove(scope.row)"
              v-hasPermi="['ruoyi:distributor:audit']"
              >通过</el-button
            >
            <el-button
              link
              type="danger"
              icon="CircleClose"
              @click="handleReject(scope.row)"
              v-hasPermi="['ruoyi:distributor:audit']"
              >拒绝</el-button
            >
          </template>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:distributor:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:distributor:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分销用户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="720px" append-to-body>
      <el-collapse v-model="activeCollapse">
        <!-- 基本信息组 -->
        <el-collapse-item name="basic" title="基本信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="分销员编号" prop="distributorCode">
                <el-input
                  v-model="form.distributorCode"
                  placeholder="DSN开头"
                  @blur="validateDistributorCode"
                >
                  <template #prepend>DSN</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="realName">
                <el-input
                  v-model="form.realName"
                  placeholder="请输入真实姓名"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="mobile">
                <el-input
                  v-model="form.mobile"
                  placeholder="请输入手机号"
                  maxlength="11"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="identityCard">
                <el-input
                  v-model="form.identityCard"
                  placeholder="请输入身份证号"
                  maxlength="18"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 等级与团队组 -->
        <el-collapse-item name="level" title="等级与团队">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="当前等级" prop="gradeId">
                <el-select
                  v-model="form.gradeId"
                  placeholder="请选择等级"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in gradeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上级分销员" prop="fatherId">
                <el-select
                  v-model="form.fatherId"
                  placeholder="请选择上级"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in distributorOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="团队总人数" prop="teamCount">
                <el-input-number
                  v-model="form.teamCount"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="直接下级人数" prop="directCount">
                <el-input-number
                  v-model="form.directCount"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 时间与状态组 -->
        <el-collapse-item name="time" title="时间与状态">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="成为分销员时间" prop="bindTime">
                <el-date-picker
                  v-model="form.bindTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最后登录时间" prop="lastLoginTime">
                <el-date-picker
                  v-model="form.lastLoginTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="认证状态" prop="authStatus">
                <el-select
                  v-model="queryParams.authStatus"
                  placeholder="请选择认证状态"
                  clearable
                >
                  <el-option
                    v-for="dict in auth_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in wdm_status"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="删除" prop="delFlag">
                <el-radio-group v-model="form.delFlag">
                  <el-radio
                    v-for="dict in del_flag"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 其他信息组 -->
        <el-collapse-item name="other" title="其他信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户ID" prop="userId">
                <el-input
                  v-model="form.userId"
                  placeholder="系统自动生成"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本号" prop="version">
                <el-input
                  v-model="form.version"
                  disabled
                  placeholder="系统自动管理"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注信息" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  rows="3"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 新增：分销钱包信息组 (保持与其他折叠面板一致的结构) -->
        <el-collapse-item name="wallet" title="分销钱包信息">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    icon="Plus"
                    @click="handleAddDistributionWallet"
                  >
                    添加
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="danger"
                    icon="Delete"
                    @click="handleDeleteDistributionWallet"
                  >
                    删除
                  </el-button>
                </el-col>
              </el-row>
              <el-table
                :data="distributionWalletList"
                :row-class-name="rowDistributionWalletIndex"
                @selection-change="handleDistributionWalletSelectionChange"
                ref="distributionWallet"
              >
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column
                  label="序号"
                  align="center"
                  prop="index"
                  width="50"
                />
                <el-table-column
                  label="可用余额"
                  prop="availableBalance"
                  width="150"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.availableBalance"
                      placeholder="请输入可用余额"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="冻结余额"
                  prop="frozenBalance"
                  width="150"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.frozenBalance"
                      placeholder="请输入冻结余额"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="累计收入"
                  prop="totalIncome"
                  width="150"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.totalIncome"
                      placeholder="请输入累计收入"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="累计提现"
                  prop="totalWithdraw"
                  width="150"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.totalWithdraw"
                      placeholder="请输入累计提现"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="最后入账时间"
                  prop="lastIncomeTime"
                  width="240"
                >
                  <template #default="scope">
                    <el-date-picker
                      clearable
                      v-model="scope.row.lastIncomeTime"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="请选择最后入账时间"
                    >
                    </el-date-picker>
                  </template>
                </el-table-column>
                <el-table-column
                  label="最后提现时间"
                  prop="lastWithdrawTime"
                  width="240"
                >
                  <template #default="scope">
                    <el-date-picker
                      clearable
                      v-model="scope.row.lastWithdrawTime"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="请选择最后提现时间"
                    >
                    </el-date-picker>
                  </template>
                </el-table-column>
                <el-table-column
                  label="状态：0-正常 1-冻结"
                  prop="walletStatus"
                  width="150"
                >
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.walletStatus"
                      placeholder="请选择状态：0-正常 1-冻结"
                    >
                      <el-option
                        v-for="dict in wallet_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="状态" prop="status" width="150">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.status"
                      placeholder="请选择状态"
                    >
                      <el-option
                        v-for="dict in wdm_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="版本号" prop="version" width="150">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.version"
                      placeholder="请输入版本号"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上级绑定对话框 -->
    <el-dialog
      title="上级绑定"
      v-model="bindParentOpen"
      width="500px"
      append-to-body
    >
      <el-form
        :model="bindParentForm"
        :rules="bindParentRules"
        ref="bindParentRef"
        label-width="100px"
      >
        <el-form-item label="当前分销员" prop="currentDistributor">
          <el-select
            v-model="bindParentForm.currentDistributorId"
            placeholder="请选择要绑定的分销员"
            style="width: 100%"
            filterable
            @change="handleCurrentDistributorChange"
          >
            <el-option
              v-for="item in distributorList"
              :key="item.distributorId"
              :label="`${item.distributorCode} - ${item.realName}`"
              :value="item.distributorId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级编号" prop="parentDistributorCode">
          <el-input
            v-model="bindParentForm.parentDistributorCode"
            placeholder="请输入上级分销员编号"
            clearable
            @blur="handleSearchParentDistributor"
          >
            <template #append>
              <el-button icon="Search" @click="handleSearchParentDistributor"
                >查询</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="上级信息"
          v-if="parentDistributorInfo.distributorId"
        >
          <div class="parent-info">
            <p>
              <strong>编号：</strong>{{ parentDistributorInfo.distributorCode }}
            </p>
            <p><strong>姓名：</strong>{{ parentDistributorInfo.realName }}</p>
            <p><strong>手机号：</strong>{{ parentDistributorInfo.mobile }}</p>
            <p><strong>等级：</strong>{{ parentDistributorInfo.gradeName }}</p>
          </div>
        </el-form-item>
        <el-form-item label="绑定备注" prop="remark">
          <el-input
            v-model="bindParentForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入绑定备注信息（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitBindParent"
            :loading="bindLoading"
            >确 定</el-button
          >
          <el-button @click="cancelBindParent">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  listDistributor,
  getDistributor,
  delDistributor,
  addDistributor,
  updateDistributor,
  updateDistributorApply,
  listDistributorSummary,
  listDistributorsBasic,
  bindSuperiorDistributor,
  getDistributorByCode,
} from "@/api/ruoyi/distributor";

const { proxy } = getCurrentInstance();
const { wdm_status, refund_audit_status, wallet_status, del_flag } =
  proxy.useDict(
    "wdm_status",
    "refund_audit_status",
    "wallet_status",
    "del_flag"
  );

// const { wdm_status, del_flag, auth_status } = proxy.useDict(
//   "wdm_status",
//   "del_flag",
//   "auth_status"
// );

const distributorList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    distributorCode: null,
    realName: null,
    mobile: null,
    identityCard: null,
    gradeId: null,
    fatherId: null,
    teamCount: null,
    directCount: null,
    bindTime: null,
    lastLoginTime: null,
    authStatus: null,
    status: null,
    delFlag: null,
    authStatus: null,
    gradeName: null,
  },
  rules: {
    userId: [{ required: true, message: "用户ID不能为空", trigger: "blur" }],
    gradeId: [
      { required: true, message: "当前等级ID不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 上级绑定相关响应式数据
const bindParentOpen = ref(false);
const bindLoading = ref(false);
const parentDistributorInfo = ref({});
const bindParentForm = ref({
  currentDistributorId: null,
  parentDistributorCode: "",
  remark: "",
});

// 上级绑定表单验证规则
const bindParentRules = {
  currentDistributorId: [
    { required: true, message: "请选择要绑定的分销员", trigger: "change" },
  ],
  parentDistributorCode: [
    { required: true, message: "请输入上级分销员编号", trigger: "blur" },
  ],
};

// 添加分销员ID-姓名映射
const distributorMap = ref({ 0: "无上级" });

// 获取分销员ID-姓名映射
const loadDistributorMap = async () => {
  try {
    const res = await listDistributorsBasic();
    if (res.code === 200 && res.data) {
      // 添加调试信息
      console.log("获取到分销员基础数据:", res.data);

      const newMap = { 0: "无上级" };
      // 确保res.data是数组
      const rows = Array.isArray(res.data) ? res.data : [];

      rows.forEach((item) => {
        // 添加额外验证
        if (item.distributorId !== undefined && item.realName) {
          newMap[String(item.distributorId)] = item.realName;
        }
      });

      // 添加调试信息
      console.log("构建的映射:", newMap);
      distributorMap.value = newMap;
      return Promise.resolve();
    } else {
      // 处理非200响应
      console.error("获取分销员基础数据失败:", res.msg || "未知错误");
      // 仍然初始化基本映射
      distributorMap.value = { 0: "无上级" };
      return Promise.reject(new Error(res.msg || "获取分销员数据失败"));
    }
  } catch (error) {
    console.error("获取分销员映射失败:", error);
    // 初始化基本映射
    distributorMap.value = { 0: "无上级" };
    return Promise.reject(error);
  }
};

// 获取上级分销员名称
const getFatherName = (fatherId) => {
  // 添加调试信息
  console.log("查找上级ID:", fatherId, "当前映射:", distributorMap.value);

  if (fatherId === undefined || fatherId === null) {
    return "未知";
  }

  const id = String(fatherId);
  const name = distributorMap.value[id];

  if (name) {
    return name;
  } else {
    // 尝试数字ID匹配（兼容可能的数据类型问题）
    const numId = Number(fatherId);
    if (!isNaN(numId) && distributorMap.value[String(numId)]) {
      return distributorMap.value[String(numId)];
    }
    return `ID: ${fatherId}`;
  }
};

const activeCollapse = ref(["basic", "level", "time", "other"]);
const gradeOptions = ref([]);
const distributorOptions = ref([]);

// 分销员编号验证
function validateDistributorCode() {
  if (
    form.value.distributorCode &&
    !form.value.distributorCode.startsWith("DSN")
  ) {
    proxy.$modal.msgError("分销员编号必须以DSN开头");
    form.value.distributorCode =
      "DSN" + form.value.distributorCode.replace(/[^0-9]/g, "");
  }
}

// 新增：搜索区域折叠/展开
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

// 通过审核
function handleApprove(row) {
  proxy.$modal.confirm("确定要通过该分销员的申请吗？").then(function () {
    const data = {
      distributorId: row.distributorId,
      authStatus: "1", // 1表示已通过
    };
    updateDistributorApply(data).then((response) => {
      proxy.$modal.msgSuccess("审核通过");
      getList();
    });
  });
}

// 拒绝审核
function handleReject(row) {
  proxy.$modal
    .prompt("请输入拒绝理由", "拒绝审核", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /.{1,200}$/,
      inputErrorMessage: "拒绝理由不能为空，且不超过200个字符",
    })
    .then(({ value }) => {
      const data = {
        distributorId: row.distributorId,
        authStatus: "2", // 2表示未通过
        rejectReason: value,
      };
      updateDistributorApply(data).then((response) => {
        proxy.$modal.msgSuccess("已拒绝审核");
        getList();
      });
    })
    .catch(() => {});
}

/** 查询分销用户信息列表 */
function getList() {
  loading.value = true;
  // 1. 先加载映射数据
  loadDistributorMap()
    .then(() => {
      // 2. 确保映射加载完成后再查询列表
      return listDistributorSummary(queryParams.value);
    })
    .then((response) => {
      // 3. 过滤数据
      distributorList.value = response.rows.filter(
        (item) => item.delFlag !== "2"
      );
      total.value = response.total;
    })
    .catch((error) => {
      console.error("获取数据失败:", error);
      // 4. 添加用户提示
      proxy.$modal.msgError("数据加载失败，请重试");
    })
    .finally(() => {
      // 5. 确保最后设置loading状态
      loading.value = false;
    });
}
// function getList() {
//   loading.value = true;
//   listDistributorSummary(queryParams.value).then((response) => {
//     distributorList.value = response.rows.filter(
//       (item) => item.delFlag !== "2"
//     );
//     total.value = response.total;
//     loading.value = false;
//   });
// }

// function getList() {
//   loading.value = true;
//   listDistributor(queryParams.value).then((response) => {
//     // distributorList.value = response.rows
//     distributorList.value = response.rows.filter(
//       (item) => item.delFlag !== "2"
//     );
//     total.value = response.total;
//     loading.value = false;
//   });
// }

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    distributorId: null,
    userId: null,
    distributorCode: null,
    realName: null,
    mobile: null,
    identityCard: null,
    gradeId: null,
    fatherId: null,
    teamCount: null,
    directCount: null,
    bindTime: null,
    lastLoginTime: null,
    status: null,
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("distributorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.distributorId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加分销用户信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _distributorId = row.distributorId || ids.value;
  getDistributor(_distributorId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改分销用户信息";
  });
}

/** 提交按钮 */
// 需要将查询表单中的queryRef改为distributorRef
function submitForm() {
  proxy.$refs["distributorRef"].validate((valid) => {
    if (valid) {
      if (form.value.distributorId != null) {
        updateDistributor(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDistributor(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _distributorIds = row.distributorId || ids.value;
  proxy.$modal
    .confirm(
      '是否确认删除分销用户信息编号为"' + _distributorIds + '"的数据项？'
    )
    .then(function () {
      return delDistributor(_distributorIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/distributor/export",
    {
      ...queryParams.value,
    },
    `distributor_${new Date().getTime()}.xlsx`
  );
}

/** 分销钱包序号 */
function rowDistributionWalletIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 分销钱包添加按钮操作 */
function handleAddDistributionWallet() {
  let obj = {};
  obj.availableBalance = "";
  obj.frozenBalance = "";
  obj.totalIncome = "";
  obj.totalWithdraw = "";
  obj.lastIncomeTime = "";
  obj.lastWithdrawTime = "";
  obj.walletStatus = "";
  obj.status = "";
  obj.version = "";
  obj.remark = "";
  distributionWalletList.value.push(obj);
}

/** 分销钱包删除按钮操作 */
function handleDeleteDistributionWallet() {
  if (checkedDistributionWallet.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的分销钱包数据");
  } else {
    const distributionWallets = distributionWalletList.value;
    const checkedDistributionWallets = checkedDistributionWallet.value;
    distributionWalletList.value = distributionWallets.filter(function (item) {
      return checkedDistributionWallets.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleDistributionWalletSelectionChange(selection) {
  checkedDistributionWallet.value = selection.map((item) => item.index);
}

// 上级绑定相关方法

/** 上级绑定按钮操作 */
function handleBindParent() {
  bindParentOpen.value = true;
  resetBindParentForm();
}

/** 重置上级绑定表单 */
function resetBindParentForm() {
  bindParentForm.value = {
    currentDistributorId: null,
    parentDistributorCode: "",
    remark: "",
  };
  parentDistributorInfo.value = {};
  proxy.$refs["bindParentRef"]?.resetFields();
}

/** 当前分销员选择变化 */
function handleCurrentDistributorChange(distributorId) {
  console.log("选择的分销员ID:", distributorId);
}

/** 搜索上级分销员 */
function handleSearchParentDistributor() {
  const distributorCode = bindParentForm.value.parentDistributorCode?.trim();
  if (!distributorCode) {
    proxy.$modal.msgWarning("请输入上级分销员编号");
    return;
  }

  bindLoading.value = true;
  getDistributorByCode(distributorCode)
    .then((response) => {
      if (response.code === 200 && response.data) {
        parentDistributorInfo.value = response.data;
        proxy.$modal.msgSuccess("查询成功");
      } else {
        parentDistributorInfo.value = {};
        proxy.$modal.msgError(response.msg || "未找到对应的分销员");
      }
    })
    .catch((error) => {
      console.error("查询分销员失败:", error);
      parentDistributorInfo.value = {};
      proxy.$modal.msgError("查询失败，请检查分销员编号是否正确");
    })
    .finally(() => {
      bindLoading.value = false;
    });
}

/** 提交上级绑定 */
/** 提交上级绑定 */
function submitBindParent() {
  proxy.$refs["bindParentRef"].validate((valid) => {
    if (valid) {
      // 验证上级分销员信息
      if (!parentDistributorInfo.value.distributorId) {
        proxy.$modal.msgWarning("请先查询并确认上级分销员信息");
        return;
      }

      // 验证不能绑定自己
      if (
        bindParentForm.value.currentDistributorId ===
        parentDistributorInfo.value.distributorId
      ) {
        proxy.$modal.msgError("不能将自己绑定为自己的上级");
        return;
      }

      bindLoading.value = true;

      // 修改这里：使用正确的参数名
      const bindData = {
        superiorDistributorCode: bindParentForm.value.parentDistributorCode,
        remark: bindParentForm.value.remark || "管理员手动绑定上级关系",
      };

      bindSuperiorDistributor(bindData)
        .then((response) => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("上级绑定成功");
            bindParentOpen.value = false;
            getList(); // 刷新列表
          } else {
            proxy.$modal.msgError(response.msg || "绑定失败");
          }
        })
        .catch((error) => {
          console.error("绑定失败:", error);
          proxy.$modal.msgError("绑定失败，请重试");
        })
        .finally(() => {
          bindLoading.value = false;
        });
    }
  });
}

/** 取消上级绑定 */
function cancelBindParent() {
  bindParentOpen.value = false;
  resetBindParentForm();
}

getList();
</script>

<style scoped>
/* 搜索卡片样式 */
.search-card {
  /* margin-bottom: 16px; */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.collapse-btn {
  padding: 0;
  font-size: 14px;
  color: #606266;
}
</style>
